<template>
  <div class="container">
    <div class="handle-box">
      <el-button
        type="success"
        size="mini"
        icon="el-icon-plus"
        @click="handleAdd"
        >新增</el-button
      >
    </div>
    <el-table
      highlight-current-row
      :data="
        tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
      "
    >
      <el-table-column prop="ID" label="角色ID"></el-table-column>
      <el-table-column prop="NAME" label="角色名称"></el-table-column>
      <el-table-column prop="RLEVEL_NAME" label="角色级别"></el-table-column>
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <!-- <el-button
            type="text"
            @click="handleDelete(scope.$index, scope.row)"
            style="color: red"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    <!-- 编辑弹出框 -->
    <el-dialog
      :title="editDialogTitle"
      :visible.sync="isVisibleEdit"
      width="50%"
    >
      <el-form ref="form" :model="form" label-width="100px" class="flex">
        <!-- <el-form-item label="角色ID：" class="wid50">
          <el-input
            v-model="form.ID"
            placeholder="请输入角色ID"
            class="handle-input mr10"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="角色名称：" class="wid50">
          <el-input
            v-model="form.NAME"
            placeholder="请输入角色名称"
            class="handle-input mr10"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色级别：" class="wid50">
          <el-select
            v-model="form.RLEVEL"
            placeholder="请选择"
            @change="changerole"
          >
            <el-option
              v-for="(item, index) in rolelevel"
              :key="index"
              :label="item.roleleveltitle"
              :value="item.rolelevelindex"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-form label-width="100px" class="flex">
        <el-form-item label="功能页面：" class="wid50">
          <div style="margin: 15px 0"></div>
          <el-tree
            :data="data"
            show-checkbox
            node-key="functionID"
            ref="tree"
            accordion
            :default-expanded-keys="checkedCities"
            :default-checked-keys="checkedCities"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisibleEdit = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

import '@/assets/css/common.css'

export default {
  data () {
    return {
      currentPage: 1, //初始页
      pageSize: 10,    //    每页的数据
      tableData: [],
      data: [],
      rolelevel: [{
        roleleveltitle: '系统管理员',
        rolelevelindex: '-1'
      }, {
        roleleveltitle: '项目管理员',
        rolelevelindex: '0'
      }, {
        roleleveltitle: '机扫',
        rolelevelindex: '1'
      }, {
        roleleveltitle: '垃圾',
        rolelevelindex: '2'
      }, {
        roleleveltitle: '人工',
        rolelevelindex: '3'
      }, {
        roleleveltitle: '公厕维保',
        rolelevelindex: '4'
      }],
      defaultProps: {
        children: 'subs',
        label: 'title'
      },
      editDialogTitle: '',
      isVisibleEdit: false,
      form: {},
      checkedCities: [],
    }
  },
  created () {
    this.getRoleList()
    this.GetFunctionListForRoleManage()
    Array.prototype.indexOf = function (val) {
      for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
      }
      return -1;
    }
    Array.prototype.remove = function (val) {
      var index = this.indexOf(val);
      if (index > -1) {
        this.splice(index, 1);
      }
    };
  },
  methods: {
    async GetFunctionListForRoleManage () {
      var url = 'Role/GetFunctionListForRoleManage?userName=' + localStorage.getItem('LOGIN_NAME')
      const { data } = await this.$Http.get(url)
      this.data = data
    },
    async getRoleList () {
      this.currentPage = 1
      // var url = 'Role/GetRoleInfoList'
      var url = 'Role/GetRoleInfoListByUserID?UID=' + localStorage.getItem('LOGIN_NAME')
      const { data } = await this.$Http.get(url)
      this.tableData = data
      this.tableData.map(function (val) {
        if (val.RLEVEL == -1) {
          val.RLEVEL_NAME = '系统管理员'
        } else if (val.RLEVEL == 0) {
          val.RLEVEL_NAME = '项目管理员'
        } else if (val.RLEVEL == 1) {
          val.RLEVEL_NAME = '机扫'
        } else if (val.RLEVEL == 2) {
          val.RLEVEL_NAME = '垃圾'
        } else if (val.RLEVEL == 3) {
          val.RLEVEL_NAME = '人工'
        } else if (val.RLEVEL == 4) {
          val.RLEVEL_NAME = '公厕维保'
        }
      })
    },
    // 打开新增窗口
    handleAdd () {
      this.editDialogTitle = '新增角色'
      //清空编辑框
      this.form = {}
      //清空树节点
      if (this.checkedCities.length) {
        this.$refs.tree.setCheckedKeys([]);
        this.checkedCities = []
      }
      //展示窗口
      this.isVisibleEdit = true;
    },
    // 打开编辑窗口
    handleEdit (index, row) {
      // this.form = row;
      this.form = Object.assign({}, row);
      //清空树节点
      if (this.checkedCities.length) {
        this.$refs.tree.setCheckedKeys([]);
        this.checkedCities = []
      }
      this.checkedCities = row.FUNCTION_ID.split('、')
      this.editDialogTitle = '编辑角色'
      this.isVisibleEdit = true;
    },
    // 点击保存，判断是新增还是编辑操作
    handleSubmit () {
      if (this.editDialogTitle == '新增角色') {
        this.saveAdd()
      } else {
        this.saveEdit()
      }
    },
    // 保存新增
    async saveAdd () {
      var array = this.$refs.tree.getCheckedKeys()
      var arrayset = [...new Set(array)]

      const params = {
        FUNCTION_ID: arrayset.join("、"),
        RLEVEL: this.form.RLEVEL,
        NAME: this.form.NAME
      }
      console.log('新增角色参数：')
      console.log(params)

      this.$axios({
        url: 'Role/AddRoleInfo',
        method: 'post',
        data: params,
      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('新增成功')
          this.isVisibleEdit = false
          this.getRoleList()
        } else {
          this.$message.error('已存在此角色名称，请重新填入未使用的角色名称')
        }
      })
    },
    // 保存编辑
    async saveEdit () {
      var array = this.$refs.tree.getCheckedKeys()
      var arr = [...new Set(array)]

      const params = {
        FUNCTION_ID: arr.join('、'),
        ID: this.form.ID,
        NAME: this.form.NAME,
        RLEVEL: this.form.RLEVEL,
      }
      // console.log(params)
      this.$axios({
        url: 'Role/UpdataRoleFunctionPost',
        method: 'post',
        data: params,
      }).then((res) => {
        console.log(this.data)
        console.log(res)
        if (res.data.IsSucess) {
          this.$message.success('编辑成功')
          this.isVisibleEdit = false
          this.getRoleList()
        } else {
          this.$message.error('此角色名称已存在，请重新填入未使用的角色名称')
        }
      })
    },
    // 删除角色
    async handleDelete (index, row) {
      const confirmResult = await this.$confirm('确定删除？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult == 'confirm') {
        const params = {
          ID: row.ID,
        }
        const { data } = await this.$Http.get('Role/DeleteRoleInfo', { params })
        if (data.IsSucess) {
          this.$message.success('删除成功')
          this.isVisibleEdit = false
          this.getRoleList()
        } else {
          this.$message.error('删除失败');
        }
      } else {
        this.$message.info('取消删除')
        this.isVisibleEdit = false
      }

    },
    // 分页导航
    handlePageChange (currentPage) {
      this.currentPage = currentPage;
    },
    handleSizeChange (size) {
      this.pageSize = size;
    }
  }
}
</script>
<style scoped lang="less">
/deep/.el-table th {
  height: 42px;
}
.el-select {
  width: 100%;
  max-width: 200px;
}
.el-input {
  width: 100%;
  max-width: 200px;
}
/deep/.el-dialog__body {
  height: 400px;
  overflow-y: scroll;
}
</style>